package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.bean.JsonResult;
import com.qf.pojo.Goods;
import com.qf.pojo.GoodsCategory;
import com.qf.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("findByPage")
    @ResponseBody
    public JsonResult findByPage(
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "limit", required = false, defaultValue = "5") Integer pageSize
    ) {

        JsonResult ok = JsonResult.ok();

        PageHelper.startPage(pageNum, pageSize);

        List<Goods> goods = goodsService.findAll();

        PageInfo<Goods> goodsPageInfo = new PageInfo<>(goods);

        ok.setCount(goodsPageInfo.getTotal());
        ok.setData(goodsPageInfo.getList());

        return ok;

    }

    @RequestMapping("deleteAll")
    @ResponseBody
    public String deleteAll(Integer[] goodIds) {
        System.out.println("controller deleteAll()" + Arrays.toString(goodIds));
        goodsService.deleteAll(goodIds);
        return "success";
    }


    @RequestMapping("deleteGoodsById")
    @ResponseBody
    public String deleteGoodsById(Integer id) {

        System.out.println("controller deleteById()" + id);
        goodsService.deleteById(id);

        return "success";
    }

    @RequestMapping("addGoods")
    public String addUser(Goods goods) {
        System.out.println(goods);

        goodsService.addGoods(goods);

        return "redirect:/index.html";
    }

    @RequestMapping("updateGoods")
    @ResponseBody
    public String updateGoods(Goods goods) {

        System.out.println("controller updateGoods() " + goods);

        goodsService.updateGoods(goods);
        return "success";
    }

    @RequestMapping("findGoodsCategory")
    @ResponseBody
    public List<GoodsCategory> findGoodsCategory() {

        List<GoodsCategory> list = goodsService.findGoodsCategory();

        return list;
    }
}
